<template>
	<el-drawer v-model="visible" size="100%" :destroy-on-close="true" :show-close="false">
		<template #header="{ close, titleId, titleClass }">
			<span :id="titleId" :class="titleClass">{{ titleDrawer }}</span>
			<el-button class="btnReturn" @click="close">返回</el-button>
		</template>
		<div v-if="visible">
			<el-form ref="basicDataFormRef" :rules="basicDataFormRules" :model="basicDataForm" label-width="120px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="basicDataForm.name" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item label="api路径" prop="path">
					<fast-select
						v-model="basicDataForm.type"
						dict-type="api_type"
						placeholder="请求方式"
						:disabled="handleType == 'test'"
						clearable
						filterable
						style="width: 100px"
					></fast-select>
					<el-input :style="{ width: 'calc(100% - 100px)' }" v-model="basicDataForm.path" placeholder="api路径">
						<template #prepend>{{ ipPortAddress }}</template>
					</el-input>
					<!-- <el-input :style="{ width: dataForm.id ? 'calc(100% - 100px)' : 'calc(100% - 180px)' }" v-model="basicDataForm.path" placeholder="api路径">
						<template #prepend>{{ ipPortAddress }}</template>
					</el-input> -->
					<!-- <el-button type="primary" style="position: absolute; right: 0" v-if="!dataForm.id || handleType != 'edit'" @click="clickRequest"
						>运行</el-button
					> -->
				</el-form-item>
				<!-- <el-form-item label="请求方式" prop="type">
					<fast-select v-model="basicDataForm.type" dict-type="api_type" placeholder="请选择" clearable
						filterable></fast-select>
				</el-form-item> -->
				<el-form-item label="描述" prop="note">
					<el-input v-model="basicDataForm.note" :rows="2" type="textarea" placeholder="描述" />
				</el-form-item>
			</el-form>
			<el-form ref="apiSqlFormRef" :rules="apiSqlFormRules" :model="apiSqlForm" label-width="120px">
				<el-form-item label="选择库表" prop="databaseId" v-if="apiSqlForm.sqlDbType == '1'">
					<el-select v-model="apiSqlForm.databaseId" clearable filterable placeholder="请选择数据库" @change="databaseChange">
						<!-- :label="`[${item.id}]${item.name}`" -->
						<el-option v-for="(item, index) in apiSqlForm.databaseList" :key="item.id" :label="`${item.name}`" :value="item.id"></el-option>
					</el-select>
					<el-button style="margin-left: 20px" :icon="Search" type="primary" @click="dbLook()">库表信息</el-button>
				</el-form-item>
				<el-form-item label="sql分隔符" prop="sqlSeparator" v-if="apiSqlForm.sqlDbType == '1'">
					<el-tooltip class="box-item" effect="dark" content="sql 语句将按照填写的 sql 分割符进行分割" placement="top-end">
						<el-input v-model="apiSqlForm.sqlSeparator">
							<template #prepend>sql分割符:</template>
						</el-input>
					</el-tooltip>
				</el-form-item>
				<el-form-item label="开启事务" prop="openTrans" v-if="apiSqlForm.sqlDbType == '1'">
					<el-tooltip effect="dark" content="如果数据库本身不支持事务, 则不要开启" placement="top-end">
						<el-switch v-model="apiSqlForm.openTrans" :active-value="1" :inactive-value="0" />
					</el-tooltip>
				</el-form-item>
				<el-form-item label="查询最大行数" prop="sqlMaxRow" v-if="apiSqlForm.sqlDbType == '1'">
					<el-tooltip effect="dark" content="select语句查询返回的最大行数" placement="top-end">
						<el-input-number v-if="databaseType == 4" v-model="apiSqlForm.sqlMaxRow" :min="100" :max="1000"></el-input-number>
						<el-input-number v-else v-model="apiSqlForm.sqlMaxRow" :min="1" :max="1000" />
					</el-tooltip>
				</el-form-item>
				<el-form-item label="权限" prop="previlege" v-if="apiSqlForm.sqlDbType == '1' || apiSqlForm.sqlDbType == '2'">
					<el-tooltip
						class="box-item"
						effect="dark"
						content="开放接口可以直接访问, 私有接口需要在请求头携带 token 访问, 请前往 API 权限菜单查看"
						placement="top-end"
					>
						<el-radio-group v-model="apiSqlForm.previlege">
							<el-radio :label="0" border>开放</el-radio>
							<el-radio :label="1" border>私有</el-radio>
						</el-radio-group>
					</el-tooltip>
				</el-form-item>
				<div>请求头：</div>
				<el-form-item label="Content-Type" prop="contentType" v-if="apiSqlForm.sqlDbType == '1' || apiSqlForm.sqlDbType == '2'">
					<fast-select :disabled="handleType == 'test'" v-model="apiSqlForm.contentType" dict-type="content_type" style="width: 100%"></fast-select>
				</el-form-item>
				<el-form-item label="请求头参数" prop="requestHeader" v-if="apiSqlForm.previlege == 1 && handleType == 'test'">
					<div v-for="(item, index) in requestHeaderList" style="display: flex; width: 100%; align-items: center; margin-bottom: 10px">
						<el-select v-model="item.header" filterable style="width: 300px">
							<el-option label="Accept" value="Accept"></el-option>
							<el-option label="Accept-Charset" value="Accept-Charset"></el-option>
							<el-option label="Accept-Encoding" value="Accept-Encoding"></el-option>
							<el-option label="Accept-Language" value="Accept-Language"></el-option>
							<el-option label="Access-Control-Request-Headers" value="Access-Control-Request-Headers"></el-option>
							<el-option label="Access-Control-Request-Method" value="Access-Control-Request-Method"></el-option>
							<el-option label="Authorization" value="Authorization"></el-option>
							<el-option label="Cache-Control" value="Cache-Control"></el-option>
							<el-option label="Connection" value="Connection"></el-option>
							<el-option label="Content-MD5" value="Content-MD5"></el-option>
							<el-option label="Content-Length" value="Content-Length"></el-option>
							<el-option label="Content-Type" value="Content-Type"></el-option>
							<el-option label="Cookie" value="Cookie"></el-option>
							<el-option label="Referer" value="Referer"></el-option>
							<el-option label="Host" value="Host"></el-option>
							<el-option label="If-Modified-Since" value="If-Modified-Since"></el-option>
							<el-option label="If-None-Match" value="If-None-Match"></el-option>
							<el-option label="Keep-Alive" value="Keep-Alive"></el-option>
							<el-option label="Origin" value="Origin"></el-option>
							<el-option label="User-Agent" value="User-Agent"></el-option>
							<el-option label="X-Requested-With" value="X-Requested-With"></el-option>
							<el-option label="X-Forwarded-For" value="X-Forwarded-For"></el-option>
							<el-option label="X-Forwarded-Proto" value="X-Forwarded-Proto"></el-option>
							<el-option label="X-Forwarded-Host" value="X-Forwarded-Host"></el-option>
						</el-select>
						<el-input v-model="item.value" style="width: 100%"></el-input>
						<el-icon @click="addHeaderData" :size="24" style="cursor: pointer; margin-left: 10px"><CirclePlus /></el-icon>
						<el-icon @click="delHeaderData(index)" v-if="!(requestHeaderList.length == 1)" :size="24" style="cursor: pointer; margin-left: 10px"
							><Remove
						/></el-icon>
					</div>
				</el-form-item>
				<!-- <el-form-item prop="requestValue">
					<el-input v-model="apiSqlForm.requestValue"></el-input>
				</el-form-item> -->
				<el-form-item label="ApiToken" prop="apiToken" v-if="apiSqlForm.previlege == 1 && handleType == 'test'">
					<el-input v-model="apiSqlForm.apiToken" style="width: calc(100% - 110px)"></el-input>
					<el-button style="position: absolute; right: 0" type="primary" @click="requestToken()">获取token</el-button>
				</el-form-item>
				<!-- sql 编辑器 -->
				<div v-if="apiSqlForm.sqlDbType == '1'">sql语句：</div>
				<el-form-item label="" prop="sqlText" v-if="apiSqlForm.sqlDbType == '1'">
					<SqlStudio ref="sqlStudioRef" style="width: 100%"></SqlStudio>
				</el-form-item>
				<el-form-item label="请求参数示例" prop="jsonParam" v-if="apiSqlForm.sqlDbType == '1' || apiSqlForm.sqlDbType == '2'">
					<ParamStudio id="requestParamStudio" ref="requestParamRef" style="height: 160px; width: 100%"> </ParamStudio>
				</el-form-item>
				<el-divider />
				<el-form-item label="响应结果示例" prop="responseResult" v-if="apiSqlForm.sqlDbType == '1' || apiSqlForm.sqlDbType == '2'">
					<ParamStudio id="responseResultStudio" ref="responseResultRef" style="height: 160px; width: 100%"> </ParamStudio>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<el-button v-if="handleType != 'test'" @click="visible = false">取消</el-button>
			<el-button v-if="handleType != 'test'" type="primary" @click="submitHandle()">提交</el-button>
			<el-button type="primary" v-if="handleType == 'test'" @click="clickRequest">运行</el-button>
		</template>
	</el-drawer>

	<el-dialog v-model="dbLookDialog" title="库表信息">
		<Databases :childProp="dataForm.parentData" ref="databasesRef" v-if="apiSqlForm.sqlDbType == 1"></Databases>
		<Middledb ref="middledbRef" v-if="apiSqlForm.sqlDbType == 2"></Middledb>
	</el-dialog>

	<SelectApp ref="selectAppRef" @close="getUrl"></SelectApp>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, provide, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { Search } from '@element-plus/icons-vue'
import { listDatabase } from '@/api/data-integrate/database'
import { useApiConfigApi, useApiConfigSubmitApi, getIpPortApi, requestTokenApi } from '@/api/data-service/apiConfig'
import Databases from '../../data-development/production/databases.vue'
import Middledb from '../../data-development/production/middledb.vue'
import SqlStudio from './sql-studio.vue'
import ParamStudio from './param-studio.vue'
import SelectApp from './select-app.vue'
import axios from 'axios'
const props = defineProps(['childProp'])
let dataForm = reactive({
	id: '',
	parentData: '',
	stateTwo: false
})

const databaseType = ref(1)

const requestHeaderList = ref([])

const databaseChange = value => {
	apiSqlForm.databaseId = value
	const data = apiSqlForm.databaseList.filter(item => item.id == value)[0]
	databaseType.value = data.databaseType

	if (databaseType.value == 4) {
		if (apiSqlForm.sqlMaxRow < 100) {
			apiSqlForm.sqlMaxRow = 100
		}
	}
}

onMounted(() => {
	//获取数据库列表
	getDatabaseList()
	getIpPort()
})
watch(
	props,
	newValue => {
		if (newValue.childProp != 1) {
			basicDataForm.name = ''
			basicDataForm.path = ''
			basicDataForm.type = ''
			basicDataForm.note = ''
			basicDataForm.status = 0
			dataForm.stateTwo = true
			// apiSqlForm.sqlDbType = ''
			apiSqlForm.sqlParam = ''
			apiSqlForm.sqlText = ''
			apiSqlForm.contentType = 'application/json'
			apiSqlForm.openTrans = 0
			apiSqlForm.jsonParam = '{}'
			apiSqlForm.responseResult = '{}'
			apiSqlForm.sqlSeparator = ';\\n'
			apiSqlForm.sqlMaxRow = 100
			apiSqlForm.databaseId = ''
			apiSqlForm.databaseList = []
			apiSqlForm.previlege = ''
			apiSqlForm.apiToken = ''
			apiSqlForm.requestHeader = ''
			apiSqlForm.requestValue = ''
			getDatabaseList()
		} else {
			dataForm.stateTwo = false
		}
	},
	{ immediate: true, deep: true }
)
//选择数据源类型
const getDatabaseList = () => {
	listDatabase().then(res => {
		apiSqlForm.databaseList = res.data
	})
}

//打开库表信息查看
const dbLookDialog = ref(false)
const dbLook = () => {
	dataForm.parentData = 'api-group-index'
	dbLookDialog.value = true
}

const emit = defineEmits(['refreshDataList', 'changeGroup'])

const visible = ref(false)

const ipPortAddress = ref('')
const getIpPort = () => {
	getIpPortApi().then(res => {
		ipPortAddress.value = res.data
	})
}

//基本信息表
const basicDataFormRef = ref()
const basicDataForm = reactive({
	name: '',
	path: '',
	type: '',
	note: '',
	status: 0
})
const basicDataFormRules = ref({
	name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	path: [
		{
			required: true,
			validator: (rule, value, callback) => {
				if (!value || !basicDataForm.type) {
					callback(new Error('必填项不能为空'))
				} else {
					callback()
				}
			},
			trigger: 'change'
		}
	]
	// type: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
//基本信息表
const apiSqlFormRef = ref()
const apiSqlForm = reactive({
	sqlDbType: '',
	sqlParam: '',
	sqlText: '\\n',
	contentType: 'application/json',
	openTrans: 0,
	jsonParam: '{}',
	responseResult: '{}',
	sqlSeparator: ';\\n',
	sqlMaxRow: 100,
	databaseId: '',
	databaseList: [],
	previlege: '',
	apiToken: '',
	requestHeader: '',
	requestValue: ''
})
const apiSqlFormRules = ref({
	sqlSeparator: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	sqlMaxRow: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	contentType: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	sqlDbType: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	databaseId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	sqlText: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	jsonParam: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	responseResult: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	previlege: [{ required: true, message: '必填项不能为空', trigger: 'change' }]
})

provide('apiSqlForm', apiSqlForm)

//代码编辑器
const sqlStudioRef = ref()

const handleType = ref('')
const titleDrawer = ref('')

const addHeaderData = () => {
	requestHeaderList.value.push({
		header: '',
		value: ''
	})

	requestHeaderList.value = [...requestHeaderList.value]
}

const delHeaderData = index => {
	requestHeaderList.value.splice(index, 1)
	requestHeaderList.value = [...requestHeaderList.value]
}

const init = (groupId: number, id: number, type: any, handType: any) => {
	visible.value = true
	dataForm.id = ''
	dataForm.groupId = groupId
	handleType.value = handType

	apiSqlForm.requestHeader = ''
	apiSqlForm.requestValue = ''

	requestHeaderList.value = []

	if (dataForm.id || handType == 'edit') {
		titleDrawer.value = '编辑'
	} else if (handType == 'add') {
		titleDrawer.value = '新增'
	} else if (handType == 'test') {
		titleDrawer.value = '测试'

		requestHeaderList.value.push({
			header: '',
			value: ''
		})
	} else {
		titleDrawer.value = '查看'
	}

	// 重置表单数据
	nextTick(() => {
		if (basicDataFormRef.value) {
			basicDataFormRef.value.resetFields()
		}
	})
	if (apiSqlFormRef.value) {
		nextTick(() => {
			apiSqlFormRef.value.resetFields()
		})
		sqlStudioRef.value.closeDebug()
		setTimeout(() => {
			sqlStudioRef.value.setSqlParam('')
			sqlStudioRef.value.setEditorValue('')
			requestParamRef.value.setEditorValue('')
			responseResultRef.value.setEditorValue('{"code":0,"msg":"success","data":[]}')
		}, 100)
	}

	if (id) {
		getApiConfig(id)
	} else {
		apiSqlForm.sqlDbType = type

		dataForm = {
			id: '',
			parentData: '',
			stateTwo: false,
			groupId: groupId
		}
	}

	// console.log(apiSqlForm)
}

const getApiConfig = (id: number) => {
	useApiConfigApi(id).then(res => {
		const resData = res.data
		Object.assign(dataForm, resData)

		basicDataForm.name = resData.name
		basicDataForm.path = resData.path
		basicDataForm.type = resData.type
		basicDataForm.note = resData.note
		basicDataForm.status = resData.status

		apiSqlForm.apiToken = ''
		apiSqlForm.sqlDbType = resData.sqlDbType
		apiSqlForm.sqlParam = resData.sqlParam
		apiSqlForm.sqlText = resData.sqlText
		apiSqlForm.contentType = resData.contentType
		apiSqlForm.openTrans = resData.openTrans
		apiSqlForm.jsonParam = resData.jsonParam
		apiSqlForm.responseResult = resData.responseResult
		apiSqlForm.sqlSeparator = resData.sqlSeparator
		apiSqlForm.sqlMaxRow = resData.sqlMaxRow
		apiSqlForm.databaseId = resData.databaseId
		apiSqlForm.previlege = resData.previlege

		if (apiSqlForm.sqlDbType == 1) {
			const sqlData = apiSqlForm.databaseList.filter(item => item.id == resData.databaseId)[0]
			databaseType.value = sqlData.databaseType

			if (databaseType.value == 4) {
				if (apiSqlForm.sqlMaxRow < 100) {
					apiSqlForm.sqlMaxRow = 100
				}
			}
		}

		setTimeout(() => {
			sqlStudioRef.value.setEditorValue(apiSqlForm.sqlText)
			sqlStudioRef.value.setSqlParam(apiSqlForm.sqlParam)
		}, 100)

		// if (apiSqlForm.sqlParam == '{}') {
		// 	setTimeout(() => {
		// 		sqlStudioRef.value.setEditorValue('')
		// 		sqlStudioRef.value.setSqlParam('')
		// 	}, 100)
		// } else {
		// 	setTimeout(() => {
		// 		sqlStudioRef.value.setEditorValue(apiSqlForm.sqlText)
		// 		sqlStudioRef.value.setSqlParam(apiSqlForm.sqlParam)
		// 	}, 100)
		// }
		setTimeout(() => {
			requestParamRef.value.setEditorValue(apiSqlForm.jsonParam)
			responseResultRef.value.setEditorValue(apiSqlForm.responseResult)
		}, 300)

		changesqlDbType(resData.sqlDbType)
	})
}

const requestParamRef = ref()
const responseResultRef = ref()

// 改变sql类型
const changesqlDbType = type => {
	if (type == '1') {
		apiSqlFormRules.value.sqlText[0].required = true
	} else {
		apiSqlFormRules.value.sqlText[0].required = false
	}
}
const tabsChangeFun = () => {
	console.log(responseResultRef.value)
}

// 表单提交
const submitHandle = async () => {
	let validate = true
	await basicDataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			ElMessage.warning('请把基本信息的必填项补充完整！')
			validate = false
			return false
		} else if (!basicDataForm.type) {
			ElMessage.warning('请选择请求方式')
			validate = false
			return false
		}
	})
	if (!validate) {
		return
	}
	apiSqlForm.sqlParam = ''
	apiSqlForm.sqlText = ''
	if (apiSqlForm.sqlDbType == '1') {
		apiSqlForm.sqlParam = sqlStudioRef.value.getSqlParam()
		apiSqlForm.sqlText = sqlStudioRef.value.getEditorValue()
	}

	apiSqlForm.jsonParam = requestParamRef.value.getEditorValue()
	apiSqlForm.responseResult = responseResultRef.value.getEditorValue()
	await apiSqlFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			ElMessage.warning('请把配置的必填项补充完整！')
			validate = false
			return false
		}
	})
	if (!validate) {
		return
	}

	Object.assign(dataForm, basicDataForm)
	Object.assign(dataForm, apiSqlForm)

	// if (!dataForm.id) {
	// 	delete dataForm.releaseTime
	// 	delete dataForm.releaseUserId
	// }

	await useApiConfigSubmitApi(dataForm)
	ElMessage.success({
		message: '操作成功',
		duration: 500,
		onClose: () => {
			visible.value = false
			emit('refreshDataList')
		}
	})
}

// const tokenUrl = ref('')
const getUrl = url => {
	// tokenUrl.value = url
	requestTokenApi(url).then(res => {
		apiSqlForm.apiToken = res.data
	})
}

const selectAppRef = ref()
const requestToken = () => {
	selectAppRef.value.init()
	// requestTokenApi('').then(res => {
	// 	apiSqlForm.apiToken = res.data
	// })
}

// 运行
const requestClient = axios.create({
	timeout: 600000
})
const clickRequest = () => {
	let jsonParam = requestParamRef.value.getEditorValue()
	jsonParam = jsonParam ? JSON.parse(jsonParam) : {}
	let reqData: any = {}
	if (requestHeaderList.value.length) {
		requestHeaderList.value.forEach(item => {
			if (item.header) {
				reqData[item.header] = item.value
			}
		})
	}
	// if (apiSqlForm.requestHeader) {
	// 	reqData[apiSqlForm.requestHeader] = apiSqlForm.requestValue
	// }
	const config = {
		headers: {
			apiToken: apiSqlForm.apiToken,
			...reqData
		}
	}

	if (basicDataForm.type == 'GET') {
		let requestStr = ''
		let i = 0
		for (let key in jsonParam) {
			if (i == 0) {
				requestStr += '?' + key + '=' + jsonParam[key]
			} else {
				requestStr += '&' + key + '=' + jsonParam[key]
			}
			i++
		}
		requestClient
			.get(ipPortAddress.value + basicDataForm.path + requestStr, config)
			.then(res => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(res.data))
			})
			.catch(err => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(err))
			})
	} else if (basicDataForm.type == 'POST') {
		requestClient
			.post(ipPortAddress.value + basicDataForm.path, jsonParam, config)
			.then(res => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(res.data))
			})
			.catch(err => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(err))
			})
	} else if (basicDataForm.type == 'PUT') {
		requestClient
			.put(ipPortAddress.value + basicDataForm.path, jsonParam, config)
			.then(res => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(res.data))
			})
			.catch(err => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(err))
			})
	} else if (basicDataForm.type == 'DELETE') {
		config.data = jsonParam
		requestClient
			.delete(ipPortAddress.value + basicDataForm.path, config)
			.then(res => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(res.data))
			})
			.catch(err => {
				responseResultRef.value.setEditorValueAndFormat(JSON.stringify(err))
			})
	}
}

const closeDraw = () => {
	visible.value = false
}

defineExpose({
	init,
	closeDraw
})
</script>
